//
//  Myuser.m
//  coba-iOS
//
//  Created by 郭四虎 on 15/12/11.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "Myuser.h"

//#import "getgateway.h"
#import <arpa/inet.h>
#import <netdb.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <ifaddrs.h>
#import <net/if.h>
//#import <SystemConfiguration/SCNetworkReachability.h>
#include <sys/socket.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

@implementation Myuser

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    if ([key isEqualToString:@"photo"]) {
        //self.icon = [NSString stringWithFormat:@"%@?url=%@",GETICON,value];
        if (![value hasPrefix:@"http"]) {
            self.icon = [NSString stringWithFormat:@"%@%@",@"http://120.26.97.23:8080",value];
        }else{
            self.icon = value;
        }
//        http://120.26.97.23:8080/cooba-uip/cooba-wifi/userfiles/coobaWifi/images/clientImg/2016/07/20160714130540.png
//        http://120.26.97.23:8080/cooba-wifi/userfiles/coobaWifi/images/clientImg/2016/07/20160714130540.png
    }
}

+(instancetype)sharedUser
{
    static Myuser *user = nil;
    if (!user) {
        user = [[self alloc]init];
    }
    return user;
}

+(BOOL)isLogined
{
    Myuser *user = [self sharedUser];
    if (user.name && user.login_id) {
        return true;
    }
    return false;
}

- (void)cleanUser
{
    self.login_id = nil;
    self.name = nil;
    self.icon = nil;
    self.phone = nil;
    self.login_date = nil;
    self.sex = nil;
    self.birthday = nil;
    self.integralTotal = nil;
    self.allTotalIntegral = nil;
}

+ (NSString *)userid:(NSString *)defaultValue
{
    if (USERID) {
        return USERID;
    }else {
        if (defaultValue) {
            
            return defaultValue;
        }
        
        return @"";
    }
}

+ (NSString *)username:(NSString *)defaultValue
{
    if (USERNAME) {
        return USERNAME;
    }else{
        if (defaultValue) {
            return defaultValue;
        }
        return @"";
    }
}

//+ (NSString *) getIPAddressIPV4 {
//    
//    NSString *address = @"error";
//    struct ifaddrs *interfaces = NULL;
//    struct ifaddrs *temp_addr = NULL;
//    int success = 0;
//    
//
////    [MyAFN POST:@"http://www.whatismyip.com.tw/" parameters:nil block:^(id responseObject) {
////        
////        NSDictionary *dic = responseObject;
////        
////    } error:^(NSError *error) {
////        
////        
////    } fromController:nil];
//    
//    
//    NSString *ip = @"";
//    // retrieve the current interfaces - returns 0 on success
//    success = getifaddrs(&interfaces);
//    if (success == 0)
//    {
//        // Loop through linked list of interfaces
//        temp_addr = interfaces;
//        //*/
//        while(temp_addr != NULL)
//        /*/
//         int i=255;
//         while((i--)>0)
//         //*/
//        {
//            if(temp_addr->ifa_addr->sa_family == AF_INET)
//            {
//                // Check if interface is en0 which is the wifi connection on the iPhone
//                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
//                {
//                    // Get NSString from C String //ifa_addr
//                    //ifa->ifa_dstaddr is the broadcast address, which explains the "255's"
//                    //                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
//                    
//                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                    
//                    //routerIP----192.168.1.255 广播地址
////                    NSLog(@"broadcast address--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);
////                    //--192.168.1.106 本机地址
////                    NSLog(@"local device ip--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);
////                    //--255.255.255.0 子网掩码地址
////                    NSLog(@"netmask--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);
////                    //--en0 端口地址
////                    NSLog(@"interface--%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
//                    
//                    
//                    ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                }
//                
//            }
//            
//            temp_addr = temp_addr->ifa_next;
//        }
//    }
//    
//    // Free memory
//    freeifaddrs(interfaces);
//    
//    
//    
//    //    in_addr_t i =inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);
//    //    in_addr_t* x =&i;
//    //
//    //
//    //    unsigned char *s=getdefaultgateway(x);
//    //    NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];
//    //    free(s);
//    return ip;
//}

+ (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
    
    if (regex != nil) {
        NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
        
        if (firstMatch) {
            NSRange resultRange = [firstMatch rangeAtIndex:0];
            NSString *result=[ipAddress substringWithRange:resultRange];
            //输出结果
            NSLog(@"%@",result);
            return YES;
        }
    }
    return NO;
}
//+ (NSString *)getIPAddress:(BOOL)preferIPv4
//{
//    NSArray *searchArray = preferIPv4 ?
//    @[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
//    @[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
//    
//    NSDictionary *addresses = [self getIPAddresses];
//    NSLog(@"addresses: %@", addresses);
//    
//    __block NSString *address;
//    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
//     {
//         address = addresses[key];
//         //筛选出IP地址格式
//         if([self isValidatIP:address]) *stop = YES;
//     } ];
//    return addresses[IOS_WIFI @"/" IP_ADDR_IPv6] ? addresses[IOS_WIFI @"/" IP_ADDR_IPv6] : @"0.0.0.0";
//}
+ (NSString *) getIPAddress
{
    NSMutableDictionary *address = [NSMutableDictionary dictionary];
    
    struct ifaddrs *interfaces;
    if (!getifaddrs(&interfaces)) {
        
        struct ifaddrs *interface;
        for (interface = interfaces; interface; interface = interface->ifa_next) {
            if (!(interface->ifa_flags&IFF_UP)) {
                continue;
            }
            const struct sockaddr_in6 *addr6= (const struct sockaddr_in6*)interface->ifa_addr;
            char addrBuf[INET6_ADDRSTRLEN];
            if (addr6 && (addr6->sin6_family == AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if (inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                    type = IP_ADDR_IPv6;
                }
                if (type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@",name,type];
                    address[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        freeifaddrs(interfaces);
    }
    
    return address[IOS_WIFI@"/"IP_ADDR_IPv6] ? address[IOS_WIFI @"/" IP_ADDR_IPv6] : @"0.0.0.0";
}
+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}


+ (void)alertWithTitle:(NSString *)title Msg:(NSString *)msg target:(UIViewController*)target action:(void (^)(void))act
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        act();
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [target presentViewController:alert animated:YES completion:nil];
}

+ (void)showRedPoint:(UIViewController *)vc index:(NSInteger)num
{
    CGFloat wid = WIDTH/vc.tabBarController.viewControllers.count;
    NSInteger index;
    if (num) {
        index = num;
    }else{
        index = vc.tabBarController.selectedIndex;

    }
    
    UIView *redP = [[UIView alloc]initWithFrame:CGRectMake(wid * index+wid/2+8, 5, 10, 10)];
    redP.backgroundColor = [UIColor redColor];
    redP.layer.cornerRadius = 5;
    redP.tag = 666;
    [vc.tabBarController.tabBar addSubview:redP];
    
}

+ (void)hideRedPoint:(UIViewController *)vc
{
    UIView *vi = [vc.tabBarController.tabBar viewWithTag:666];
    if (vi) {
        [vi removeFromSuperview];
    }
    
}

+ (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}

@end
